'use strict'

const http=require('http');

let html= `
    <!DOCTYPE html>
    <html>
        <head>
            <title>First Server</title>
        </head>
        <body>
            <div>Please follow What does Jiaran eat tonight on Bilibili  B站关注嘉然今天吃什么</div>
        </body>
    </html>
`

let routerTable = {
    '/':async (request,response)=>{
        response.setHeader('content-type','text/html;charset=utf-8');
        response.end(html)

    },
    '/x/y/z':async (request,response)=>{
        // console.log(request)0
        let bufferList=[]
        let totalLength=0
        request.on('data',chunk=>{
            
            totalLength += chunk.length
            bufferList.push(chunk)
        })

        let bodyData=null

        request.on('end',()=>{
            if(bufferList.length>0)
                bodyData=Buffer.concat(bufferList,totalLength)
            bufferList = [];
            if (bodyData) {
                response.setHeader('content-type','text/plain;charset=utf-8');
                response.end(bodyData)
            }
            else{
                response.end()
            }
        })
    },
    '/x/y':async (request,response)=>{
        response.end("-------OK-------");
    },
    '/my':async (request,response)=>{
        let wxml = `<view>哈哈哈哈哈</view>`
        response.end(wxml);
    }
}

let serv=http.createServer((request,response)=>{
    // console.log(request.url,request.headers,request.method)
    
    if (routerTable[request.url] === undefined) {
        response.statusCode=404
        response.end('page not found')
        return
    }

    routerTable[request.url](request,response)

})
serv.listen(3456)